package com.example.nowcodercommunity.controller;

import com.example.nowcodercommunity.annotation.LoginRequire;
import com.example.nowcodercommunity.entity.Comment;
import com.example.nowcodercommunity.entity.DiscussPost;
import com.example.nowcodercommunity.entity.Event;
import com.example.nowcodercommunity.event.EventProducer;
import com.example.nowcodercommunity.service.CommentService;
import com.example.nowcodercommunity.service.CommunityConstant;
import com.example.nowcodercommunity.service.DiscussPostService;
import com.example.nowcodercommunity.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;

@Controller
@RequestMapping(path = "/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    /**
     * 增加评论
     * @param discussPostId
     * @param comment
     * @return
     */
    @LoginRequire
    @RequestMapping(path = "/add/{discussPostId}",method = RequestMethod.POST)
    public String addComment(@PathVariable(name = "discussPostId") int discussPostId, Comment comment){
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);

        // 触发评论事件
        Event event = new Event()
                .setTopic(CommunityConstant.TOPIC_COMMENT)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId", discussPostId);

        if(comment.getEntityType() == CommunityConstant.ENTITY_TYPE_POST){
            DiscussPost discussPost = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(discussPost.getUserId());
        }else if(comment.getEntityType() == CommunityConstant.ENTITY_TYPE_COMMENT){
            Comment c = commentService.getCommentById(comment.getEntityId());
            event.setEntityUserId(c.getUserId());
        }
        eventProducer.fireEvent(event);

        return "redirect:/discuss/detail/" + discussPostId;
    }
}
